<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\service\TenIM;
use think\Db;

/**
 * 写手申请管理
 *
 * @icon fa fa-circle-o
 */
class Writerapply extends Backend
{

    /**
     * Writerapply模型对象
     * @var \app\admin\model\Writerapply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Writerapply;
     
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
     public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
           
            // ->join("membe x","x.membe_id=m.uid","left")     
            ->where($where)
            ->order("create_time desc")
            ->paginate($limit)->each(function ($data){
                $data["username"] = db("membe")->where("membe_id",$data["uid"])->value("username");
                $imgs = json_decode($data["img"]);
                $data["imgs"] = empty($imgs)?"":implode(",",$imgs);
                
                return $data;
            });
            
            
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    
    
       
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            
            
           $row["imgs"] =  implode(",",json_decode($row["img"]));
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            
    
            
            if($params["status"] ==0){
                $this->error("暂不支持拒绝");
            }
            
        
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            
            //订单状态更改？
         
        
           
           $openid = db("membe")->where("membe_id",$row["uid"])->value("openid");
           
       
         if($params['status'] == 1){
            $msg = '写手认证审核通过！';
            $title = "写手认证审核通过";
            // 保存写手标签
            $tags = [];
            $zids = [];
            $zsidsss = [];
        
               if(!empty($openid)){
                     $this->wx_msg($openid,$title,"请尽快完善相关约稿设置");
                }
                //同时 推送1条消息
           
                     
      
                    $new_arr_json = [];
                    $new_arr_json["type"] = 7;
                    $new_arr_json["aid"] = $row["uid"];
                    // $new_arr_json["username"] = $user['username'];
                    $new_arr_json["title"] = '你的写手认证审核已通过';//urldecode($info['title']);
                    $new_arr_json["left_1"] = "通知时间：";
                    $new_arr_json["left_1_val"] = date("Y-m-d H:i:s");
                    
                    $new_arr_json["left_2"] = "温馨提示：";
                    $new_arr_json["left_2_val"] = "请完善自己的写手设置";
                    (new TenIM)->sendUserMsg($row['uid'],"sysmsg",'type'.json_encode($new_arr_json));
                     
            
             
             db("membe")->where('membe_id',$row['uid'])->update(['is_writer'=>1,'update_time'=>time()]);
             
        }else if($params['status'] == 2){
             $msg = '原因：'.$params['refuse_msg'];
             $title = "你的写手认证审核未通过";
             if(!empty($openid)){
                     $this->wx_msg($openid,$title,$msg);
              }
              
              
                    $new_arr_json = [];
                    $new_arr_json["type"] = 8;
                    $new_arr_json["aid"] = $row["uid"];
                    // $new_arr_json["username"] = $user['username'];
                    $new_arr_json["title"] = '你的写手认证审核未通过';//urldecode($info['title']);
                    $new_arr_json["left_1"] = "失败原因：";
                    $new_arr_json["left_1_val"] =  $params['refuse_msg'];
                    
                    $new_arr_json["left_2"] = "温馨提示：";
                    $new_arr_json["left_2_val"] = "请不要灰心，重新提交试试吧";
                    (new TenIM)->sendUserMsg($row['uid'],"sysmsg",'type'.json_encode($new_arr_json));
                     
              
                     
             db("membe")->where('membe_id',$row['uid'])->update(['is_writer'=>0,'update_time'=>time()]);
        }
            
     
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    
    
     //訂閲消息消息推送
     public function wx_msg($openid,$title,$desc){ 
            $templateId = 'rw8um2woPZuyWmlZFrRYLslXmrIHd1MmcUTry7Ci3Yw';
            $data = array(
                'thing1' => array('value' => $title),
                'time3' => array('value' => date('Y-m-d H:i:s', time())),
                'thing4' => array('value' => mb_substr($desc,0,15)),
            );
            $send = array(
                "touser" => $openid,
                "page"=>"pages/index/index",
                "template_id" => $templateId,
                "data" => $data,
            );
            $access_token = getaccess_tonken();

            $data = urldecode(json_encode($send));
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
            // $ret = Http::post($url, );
            $admin = curl_get($url,$type = 'json',$data);
            return $admin;
     }
     
     
     
    

}
